import 'dart:convert';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_frontend/models/user_model.dart';
import 'package:flutter_frontend/pages/login/login_page.dart';
import 'package:flutter_frontend/utils/my_navigator_route.dart';
import 'package:flutter_frontend/utils/web_socket_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:event_bus/event_bus.dart';

class AppManager {
  static final AppManager _instance = AppManager._internal();

  factory AppManager() => _instance;

  static AppManager get sharedInstance => _instance;

  AppManager._internal() {
    EasyLoading.instance
      ..displayDuration = const Duration(milliseconds: 400)
      ..maskType = EasyLoadingMaskType.black
      ..indicatorType = EasyLoadingIndicatorType.ring
      ..loadingStyle = EasyLoadingStyle.dark;
  }

  /// event_bus
  final EventBus _eventBus = EventBus();

  EventBus get eventBus => _eventBus;

  /// uuid
  String? _uuid;

  Future<String?> get uuid async {
    if (_uuid == null) {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      _uuid = prefs.getString('UUID');
      if (_uuid == null) {
        final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
        _uuid = Platform.isAndroid ? (await deviceInfo.androidInfo).androidId : (await deviceInfo.iosInfo).identifierForVendor;
        if (_uuid != null) prefs.setString(_uuid!, 'UUID');
      }
    }
    return _uuid;
  }

  /// token
  String? _token;

  Future<String?> get token async {
    if (_token == null) {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      _token = prefs.getString('TOKEN');
    }
    return _token;
  }

  void setToken(String? token) {
    _token = token;
    if (token != null) {
      SharedPreferences.getInstance().then((SharedPreferences prefs) {
        prefs.setString('TOKEN', token);
      });
    }
  }

  /// 用户信息
  UserInfo? _userInfo;

  UserInfo? get userInfo => _userInfo;

  /// 更新用户信息
  void setUserInfo(UserInfo? userInfo) {
    _userInfo = userInfo;
    if (userInfo != null) {
      SharedPreferences.getInstance().then((SharedPreferences prefs) {
        prefs.setString('USERINFO', jsonEncode(userInfo.toJson()));
      });
    }
  }

  /// 获取上次的用户信息
  Future<UserInfo?> get lastUserInfo async {
    if (_userInfo == null) {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      String? userInfoJson = prefs.getString('USERINFO');
      if (userInfoJson != null) {
        _userInfo = UserInfo.fromJson(jsonDecode(userInfoJson));
      }
    }
    return _userInfo;
  }

  Future<void> deleteUser() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove('TOKEN');
    prefs.remove('UUID');
    prefs.remove('GRANULARITY');
    prefs.remove('USERINFO');
    _token = null;
    _uuid = null;
    _userInfo = null;
    WebSocketManager().disconnect();
    MyNavigatorRoute.push(toPage: const LoginPage());
  }

  /// 系统维护
  void systemMaintenance(String? message) {
    EasyLoading.showToast(message ?? '系统维护');
  }

  /// 退出登录
  Future<void> pushToLogin() async {
    if (_token == null) return;
    await deleteUser();
    EasyLoading.showToast('登录信息失效，请重新登录');
  }

  ///*******************************************具体业务相关*******************************************///
}
